package com.example.bbgds.test.home.controller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by zjzhu on 26/4/16.
 */
public class DateTimeController extends BroadcastReceiver {

    private ArrayList<DateTimeChangeCallback> mChangeCallbacks = new ArrayList<DateTimeChangeCallback>();
    private static DateTimeController sInstance;

    public interface DateTimeChangeCallback {
        public void onDateTimeChanged(Date date);
    }

    private DateTimeController(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_LOCALE_CHANGED);
        context.registerReceiver(this, filter);
    }

    public static synchronized DateTimeController getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new DateTimeController(context);
        }
        return sInstance;
    }

    public void addStateChangedCallback(DateTimeChangeCallback cb) {
        mChangeCallbacks.add(cb);
        cb.onDateTimeChanged(new Date(System.currentTimeMillis()));
    }

    public void removeStateChangedCallback(DateTimeChangeCallback cb) {
        if (cb != null && mChangeCallbacks.contains(cb)) {
            mChangeCallbacks.add(cb);
        }
    }

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_TIME_TICK.equals(action) || Intent.ACTION_TIME_CHANGED.equals(action)
                || Intent.ACTION_TIMEZONE_CHANGED.equals(action) || Intent.ACTION_LOCALE_CHANGED.equals(action)) {
            dispatchDateChange();
        }
    }

    /**
     * Calculate the date, lunar and week.
     */
    public void dispatchDateChange() {
        Date date = new Date(System.currentTimeMillis());
        for (DateTimeChangeCallback cb : mChangeCallbacks) {
            cb.onDateTimeChanged(date);
        }
    }
}
